/**
 * 抖音店铺体验分数据port
 */

import moment from "moment"

import type { PlasmoMessaging } from "@plasmohq/messaging"

// 数据记录
let scoreData = {}
// 体验分更新日期
let scoreDate = ""
// 详情分更新日期
let detailDate = ""
// 校验总键数
let totalKeys = 0
// 键名列表
let keysList = []
// ui实例列表 如果有多个ui实例，则需要记录每个实例的数量，当实例数为0时，清空数据
// 记录tabID
let uiInstanceMap = {}

// 初始化数据
const initData = () => {
  scoreData = {}
  scoreDate = ""
  detailDate = ""
}

// ui挂载请求
const amountUi = (tabID: number) => {
  // 如果当前为首个实例，则初始化scoreData
  if (Object.keys(uiInstanceMap).length === 0) {
    initData()
  }
  // ui挂载记录tabID
  uiInstanceMap[tabID] = {}
}

// ui卸载请求
const unmountUi = (tabID: number) => {
  console.log("卸载", tabID)
  if (!uiInstanceMap[tabID]) return
  // 在uiInstanceMap中删除tabID
  delete uiInstanceMap[tabID]
  // 如果uiInstanceMap为空，则清空scoreData
  if (Object.keys(uiInstanceMap).length === 0) {
    initData()
  }
}

// 更新scoreData
const updateScoreData = (data: any) => {
  scoreData = {
    ...scoreData,
    ...data
  }
}

// 拦截概览评分数据
// 包含更新时间， 4大主评分数据
const overviewScoreDataInspector = (url: string, response: any) => {
  // 正则匹配url
  const urlReg = new RegExp(
    `^https://fxg.jinritemai.com/governance/shop/experiencescore/getOverviewByVersion`
  )
  if (!urlReg.test(url)) return true
  const { data } = response
  // 评分数据对象
  // 店铺体验分
  const experience_score = data["experience_score"] || {}
  // 商品体验分
  const goods_score = data["goods_score"] || {}
  // 物流体验分
  const logistics_score = data["logistics_score"] || {}
  // 服务体验分
  const service_score = data["service_score"] || {}
  // 基础数据解析
  const overviewData = {
    // 更新日期
    日期: moment.unix(Number(data["update_time"] || 0)).format("YYYY-MM-DD"),
    // 店铺评分
    店铺评分: experience_score["value"] || 0,
    // 商品评分
    商品体验: goods_score["value"] || 0,
    // 物流评分
    物流体验: logistics_score["value"] || 0,
    // 服务评分
    服务体验: service_score["value"] || 0
  }
  // 写入数据更新日期
  scoreDate = overviewData["日期"]
  // 更新scoreData
  updateScoreData(overviewData)
}

// 拦截店铺评分明细数据
const shopScoreDataInspector = (url: string, response: any) => {
  // 正则匹配url
  const urlReg = new RegExp(
    `^https://fxg.jinritemai.com/governance/shop/experiencescore/getSubScoreNew`
  )
  if (!urlReg.test(url)) return true
  const { data } = response
  // 店铺基础数据记录
  const updateDate = moment
    .unix(Number(data["update_time"] || 0))
    .format("YYYY-MM-DD")
  // 记录详情更新日期
  detailDate = updateDate
  // 店铺名称
  // scoreData["店铺名称"] = data["shop_name"] || ""
  // // 店铺id
  // scoreData["店铺标识"] = data["shop_id"] || ""
  // 更新日期
  scoreData["日期"] = updateDate
  // 评分数据对象列表
  const scoreList = data["shop_analysis"] || []
  // 评分数据明细记录
  scoreList.forEach((item: any) => {
    // 一级数据记录
    const key = item["title"]
    const value = item["value"] || {}
    scoreData[key] = value["value_figure"] || 0
    // 节点得分数据
    const nodeScoreData = item['node_score_info']
    console.log(nodeScoreData, 'nodeScoreData')
    if (nodeScoreData) {
      // 记录新版的节点评分数据
      const _node_score_key = item["title"] + "得分"
      scoreData[_node_score_key] = nodeScoreData['node_score'] || 0
    }

    // 超越同行数据
    // const surpassData = item["surpass_peers"] || {}
    // 二级数据
    const subData = {}
    // subData[key + "|超越同行"] = surpassData["value_figure"] || 0
    // 二级数据分解
    // key:calculate_denominator
    if (item["calculate_denominator"]) {
      const subKey = (
        key +
        "|" +
        (item["calculate_denominator"]["sub_title"] || "")
      )
        .trim()
        .replace(/\u200b/g, "")
      subData[subKey] = item["calculate_denominator"]["value"] || 0
    }
    // key: calculate_numerator
    if (item["calculate_numerator"]) {
      item["calculate_numerator"].forEach((subItem: any) => {
        const subKey = (key + "|" + (subItem["sub_title"] || ""))
          .trim()
          .replace(/\u200b/g, "")
        subData[subKey] = subItem["value"] || 0
      })
    }
    // 更新scoreData
    updateScoreData(subData)
  })
}

// 计算数据完整率
const calculateDataCompleteRate = () => {
  if (totalKeys <= 0) return "0"
  // 已记录key的数量
  const recordKeys = Object.keys(scoreData).length
  // 计算数据完整率 (完整keys包含48小时/24小时的key个数，计算时需要减去)
  return ((recordKeys / totalKeys) * 100).toFixed(0)
}

// 监听tab关闭事件，如何tabID与uiInstanceMap键匹配，触发unmount
chrome.tabs.onRemoved.addListener((tabId) => {
  unmountUi(tabId)
})

const handler: PlasmoMessaging.PortHandler = async (req, res) => {
  const { url, response, action, data } = req.body
  const tabId = req.port.sender.tab.id
  switch (action) {
    case "clear":
      // 清空数据
      initData()
      break
    case "amount":
      // ui挂载
      amountUi(tabId)
      break
    case "setKeys":
      // 设置数据键值总量
      totalKeys = data?.count || 0
      keysList = data?.fields || []
      break
    case "inspect":
      // 轮询请求拦截处理
      const inspectors = [overviewScoreDataInspector, shopScoreDataInspector]
      for (const inspector of inspectors) {
        inspector(url, response)
      }
      break
    default:
      break
  }
  const resData = {
    data: scoreData,
    rate: calculateDataCompleteRate(),
    scoreDate: scoreDate,
    detailDate: detailDate,
    keysList
  }
  // console.log("uiMaps", uiInstanceMap)
  // console.log('解析数据', resData)
  res.send(resData)
}

export default handler
